import React, { useEffect, useRef, useState } from 'react';
import { connect } from 'dva';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import {
  Divider,
  Button,
  Tooltip,
  message,
  Popconfirm,
  Badge,
  Spin,
  Modal,
  Descriptions,
} from 'antd';
import {
  apiProduceScheduleDelete,
  apiProduceScheduleUpdate,
  apiProduceScheduleAdd,
  apiProduceScheduleGetList,
  apiProduceSchedulePush,
} from '@/services/otherServices';
import {
  PlusOutlined,
  FormOutlined,
  DeleteOutlined,
  SendOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import Search from './Search';
import { history } from 'umi';
import Detail from './Detail';
import { useRequest, useSize, useUpdateEffect } from '@umijs/hooks';
import {
  btnPermission,
  diffSubmitData,
  formatDate,
  formatDateTimeStamp,
  mergeLoading,
} from '@/utils/utils';
import moment from 'moment';
import HehDescribe from '@/components/HehDescribe';

let detailForm: any = null;

const List = (props: any) => {
  const { btnPermissionLoading, childrenCollapsed } = props;
  const actionRef = useRef<ActionType>();
  const [decVisible, setDecVisible] = useState(false);
  const [decInfo, setDecInfo] = useState(false);
  const [x, setX] = useState({ x: '100%' });
  const [visible, setVisible] = useState(false);
  const [size, setSize]: any = useState('large');
  const [searchValue, setSearchValue] = useState({});
  const [current, setCurrent] = useState(1);
  const [total, setTotal] = useState(0);
  const [pageSize, setPageSize]: any = useState(10);
  const [dataSource, setDataSource] = useState([]);
  const [editId, setEditId] = useState(undefined);
  const [orderNo, setOrderNo] = useState(undefined);
  const [editItem, setEditItem] = useState(undefined);

  /*
   * 列表请求
   * */
  const { loading: pageLoading, run: getPage } = useRequest(
    apiProduceScheduleGetList,
    {
      manual: true,
      onSuccess: (res, params) => {
        setDataSource(res.data);
        setTotal(res.total);
      },
    },
  );

  /*
   * 新建请求
   * */
  const { loading: addLoading, run: add } = useRequest(apiProduceScheduleAdd, {
    manual: true,
    debounceInterval: 500,
    loadingDelay: 200,
    onSuccess: (res, params) => {
      message.success('添加设备成功');
      setVisible(false);
      getPageData();
    },
  });

  /*
   * 编辑请求
   * */
  const { loading: updateLoading, run: update } = useRequest(
    apiProduceScheduleUpdate,
    {
      manual: true,
      debounceInterval: 500,
      loadingDelay: 200,
      onSuccess: (res, params) => {
        message.success('更新设备成功');
        setVisible(false);
        getPageData();
      },
    },
  );

  /*
   * 删除请求
   * */
  const { loading: delLoading, run: del } = useRequest(
    apiProduceScheduleDelete,
    {
      manual: true,
      loadingDelay: 200,
      onSuccess: (res, params) => {
        message.success('删除设备成功');
        if (total % 10 === 1) {
          setCurrent(current - 1);
        } else {
          getPageData();
        }
      },
    },
  );

  /*
   * 推送
   * */
  const { loading: pushLoading, run: push } = useRequest(
    apiProduceSchedulePush,
    {
      manual: true,
      debounceInterval: 500,
      loadingDelay: 200,
      onSuccess: (res, params) => {
        message.success('推送成功');
        if (total % 10 === 1) {
          setCurrent(current - 1);
        } else {
          getPageData();
        }
      },
    },
  );

  const getPageData = () => {
    getPage({
      pageNo: current,
      pageSize: pageSize,
      ...searchValue,
    });
  };

  useUpdateEffect(() => {
    getPageData();
  }, [current, pageSize, searchValue]);

  useEffect(() => {
    getPageData();
    setWidth();
  }, []);

  useUpdateEffect(() => {
    setWidth(true);
  }, [childrenCollapsed]);

  const columns: ProColumns<any>[] = [
    {
      title: '编号',
      dataIndex: 'a',
      hideInSearch: true,
      render: (text, record, index) => (
        <span>{(current - 1) * 10 + index + 1}</span>
      ),
    },
    {
      title: '公司名',
      dataIndex: 'company',
    },
    {
      title: '产线名',
      dataIndex: 'productLine',
    },
    {
      title: '订单号',
      dataIndex: 'orderNo',
    },
    {
      title: '品名',
      dataIndex: 'productName',
    },
    {
      title: '规格',
      dataIndex: 'spec',
    },
    {
      title: '排产日期',
      dataIndex: 'expectProduceDate',
      valueType: 'dateRange',
      render: text => <span>{formatDate(text)}</span>,
    },
    {
      title: '数量',
      dataIndex: 'amount',
    },
    {
      title: '推送状态',
      dataIndex: 'pushed',
      render: text => (
        <Badge
          status={text ? 'success' : 'error'}
          text={text ? '已推送' : '未推送'}
        />
      ),
    },
    {
      title: '推送时间',
      dataIndex: 'pushedTime',
      render: text => <span>{formatDate(text, 'YYYY-MM-DD HH:mm:ss')}</span>,
    },
  ];
  if (
    btnPermission(history.location.pathname, [
      'btn_prod_del',
      'btn_prod_edit',
      'btn_prod_push',
    ])
  ) {
    columns.push({
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          {btnPermission(history.location.pathname, 'btn_prod_edit') && (
            <span>
              <a
                onClick={() => {
                  if (record.expectProduceDate) {
                    record.expectProduceDate = moment(record.expectProduceDate);
                  }
                  detailForm.setFieldsValue({
                    ...record,
                  });
                  setVisible(true);
                  setEditId(record.id);
                  setOrderNo(record.orderNo);
                  setEditItem(record);
                }}
              >
                <Tooltip mouseEnterDelay={0.5} title="编辑">
                  <FormOutlined style={{ fontSize: 18 }} />
                </Tooltip>
              </a>
            </span>
          )}
          {btnPermission(history.location.pathname, 'btn_prod_del') && (
            <span>
              <Divider type="vertical" />
              <Popconfirm
                title="确认删除？"
                placement="topRight"
                okText="确认"
                cancelText="取消"
                onConfirm={() => {
                  del(record.id);
                }}
              >
                <a>
                  <Tooltip mouseEnterDelay={0.5} title="删除">
                    <DeleteOutlined style={{ fontSize: 18 }} />
                  </Tooltip>
                </a>
              </Popconfirm>
            </span>
          )}
          {btnPermission(history.location.pathname, 'btn_prod_push') && (
            <span>
              <Divider type="vertical" />
              {record.pushed ? (
                <a
                  onClick={() => {
                    Modal.confirm({
                      title: '改排产计划已推送,是否重新推送?',
                      icon: <ExclamationCircleOutlined />,
                      okText: '推送',
                      cancelText: '不推送',
                      onOk() {
                        push(record.id);
                      },
                    });
                  }}
                >
                  <Tooltip mouseEnterDelay={0.5} title="推送">
                    <SendOutlined style={{ fontSize: 18 }} />
                  </Tooltip>
                </a>
              ) : (
                <Popconfirm
                  placement="topLeft"
                  title={'确认推送?'}
                  onConfirm={() => push(record.id)}
                  okText="确认"
                  cancelText="取消"
                >
                  <a>
                    <Tooltip mouseEnterDelay={0.5} title="推送">
                      <SendOutlined style={{ fontSize: 18 }} />
                    </Tooltip>
                  </a>
                </Popconfirm>
              )}
            </span>
          )}
        </>
      ),
    });
  }

  const setWidth = (tag?: boolean) => {
    var box = document.getElementById('calculate-body');
    let width: number = box?.clientWidth || 1000;
    if (tag) {
      if (childrenCollapsed) {
        width = width + 176;
      } else {
        width = width - 176;
      }
    }
    console.log(width);
    if (width >= 1000 && width <= 1050) {
      setX({ x: `${0.19 * width}%` });
    } else if (width > 1050 && width <= 1100) {
      setX({ x: `${0.185 * width}%` });
    } else if (width > 1100 && width <= 1150) {
      setX({ x: `${0.15 * width}%` });
    } else if (width > 1150 && width <= 1200) {
      setX({ x: `${0.14 * width}%` });
    } else if (width > 1200 && width <= 1300) {
      setX({ x: `${0.125 * width}%` });
    } else if (width > 1600 && width <= 1650) {
      setX({ x: `138%` });
    } else {
      setX({ x: `100%` });
    }
  };

  return (
    <div id={'calculate-body'} className={'spin-bg-white'}>
      <Spin tip={'权限获取中,请稍等...'} spinning={btnPermissionLoading}>
        <HehDescribe
          data={decInfo}
          columns={columns}
          visible={decVisible}
          onCancel={() => setDecVisible(false)}
        />
        <Detail
          afterClose={() => {
            setEditId(undefined);
            setOrderNo(undefined);
            setEditItem(undefined);
            detailForm.resetFields();
          }}
          visible={visible}
          onCancel={() => setVisible(false)}
          getForm={(from: any) => (detailForm = from)}
          loading={mergeLoading(addLoading, updateLoading)}
          editId={editId}
          orderNo={orderNo}
          onOk={async () => {
            await detailForm.validateFields();
            const value = detailForm.getFieldsValue();
            if (value.expectProduceDate) {
              value.expectProduceDate = formatDateTimeStamp(
                value.expectProduceDate,
              );
            }
            if (editId) {
              const data = diffSubmitData(editItem, value);
              update({
                id: editId,
                ...data,
              });
            } else {
              add(value);
            }
          }}
        />
        <ProTable<any>
          loading={pageLoading}
          scroll={{ x: 'max-content' }}
          dataSource={dataSource}
          expandable={{
            expandedRowRender: (record: any) => (
              <div style={{ padding: 16 }}>
                <Descriptions>
                  <Descriptions.Item
                    style={{ padding: 0 }}
                    span={3}
                    label="备注"
                  >
                    {record.remark}
                  </Descriptions.Item>
                </Descriptions>
              </div>
            ),
            rowExpandable: (record: any) => true,
          }}
          actionRef={actionRef}
          tableAlertRender={false}
          search={false}
          options={{
            fullScreen: false,
            density: true,
            reload: false,
            setting: true,
          }}
          rowKey="id"
          size={size}
          onSizeChange={(s: any) => {
            setSize(s);
          }}
          onRow={record => {
            return {
              onDoubleClick: event => {
                setDecVisible(true);
                setDecInfo(record);
              },
            };
          }}
          headerTitle={
            <Search
              loading={pageLoading}
              current={current}
              pageSize={pageSize}
              searchValue={searchValue}
              callbackValue={(value: any) => {
                setCurrent(1);
                setSearchValue(value);
              }}
            />
          }
          toolBarRender={(action, { selectedRows }) => [
            btnPermission(history.location.pathname, 'btn_prod_add') && (
              <Button
                onClick={() => setVisible(true)}
                icon={<PlusOutlined />}
                type="primary"
              >
                新建
              </Button>
            ),
          ]}
          pagination={{
            pageSize: pageSize,
            total: total,
            current: current,
            onChange: (page, pageSize) => {
              setCurrent(page);
              setPageSize(pageSize);
            },
            onShowSizeChange: (current, size) => {
              setCurrent(current);
              setPageSize(size);
            },
          }}
          columns={columns}
        />
      </Spin>
    </div>
  );
};
export default connect(({ globalModel, MainLayoutModel }: any) => ({
  btnPermissionLoading: globalModel.btnPermissionLoading,
  childrenCollapsed: MainLayoutModel.childrenCollapsed,
}))(List);
